﻿#if __ANDROID__
#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2016, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>$CreationDate$</CreationDate>
</File>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;

using Android.App;
using Android.Content;
using Android.Locations;
using Android.OS;

using Outcoder.ApplicationModel;
using Outcoder.ComponentModel;
using Outcoder.Concurrency;
using Outcoder.Messaging;

namespace Outcoder.GeoLocation
{
	public class GeoLocator : Java.Lang.Object, IGeoLocator, ILocationListener
		, IMessageSubscriber<ApplicationLifeCycleMessage>
	{
		LocationManager locationManager;
		string locationProvider;

		readonly PropertyChangeNotifier notifier;
		bool monitoring;

		public GeoLocator()
		{
			notifier = new PropertyChangeNotifier(this, false);
		}
		
		void InitializeLocationManager()
		{
			var context = Application.Context;
			locationManager = (LocationManager)context.GetSystemService(Context.LocationService);
			Criteria criteriaForLocationService = new Criteria
			{
				Accuracy = desiredAccuracy.ToAccuracy()
			};

			IList<string> acceptableLocationProviders = locationManager.GetProviders(criteriaForLocationService, true);

			if (acceptableLocationProviders.Any())
			{
				locationProvider = acceptableLocationProviders.First();
			}
			else
			{
				locationProvider = string.Empty;
			}

			locationManager.RequestLocationUpdates(locationProvider, 0, 0, this);
		}

		void StopMonitoring()
		{
			locationManager.RemoveUpdates(this);

			monitoring = false;
		}

		PositionAccuracy desiredAccuracy;

		public PositionAccuracy DesiredAccuracy
		{
			get
			{
				return desiredAccuracy;
			}
			set
			{
				notifier.Assign(ref desiredAccuracy, value);
			}
		}

		PositionStatus locationStatus;

		public PositionStatus LocationStatus
		{
			get
			{
				return locationStatus;
			}
			private set
			{
				notifier.Assign(ref locationStatus, value);
			}
		}

		double movementThresholdMeters;

		public double MovementThresholdMeters
		{
			get
			{
				return movementThresholdMeters;
			}
			set
			{
				notifier.Assign(ref movementThresholdMeters, value);
			}
		}

		uint reportInterval;

		public uint ReportInterval
		{
			get
			{
				return reportInterval;
			}
			set
			{
				notifier.Assign(ref reportInterval, value);
			}
		}

		GeopositionWrapper geoposition;

		public GeopositionWrapper Geoposition
		{
			get
			{
				return geoposition;
			}
			set
			{
				notifier.Assign(ref geoposition, value);
			}
		}

		public event EventHandler<PositionChangedProxyEventArgs> PositionChanged;

		protected virtual void OnPositionChanged(PositionChangedProxyEventArgs e)
		{
			PositionChanged?.Invoke(this, e);
		}

		public event EventHandler<StatusChangedProxyEventArgs> StatusChanged;

		protected virtual void OnStatusChanged(StatusChangedProxyEventArgs e)
		{
			StatusChanged?.Invoke(this, e);
		}

		public Task<GeopositionWrapper> GetGeoCoordinateAsync()
		{
			return Task.FromResult(geoposition);
		}

		public Task<GeopositionWrapper> GetGeoCoordinateAsync(TimeSpan maximumAge, TimeSpan timeout)
		{
			return GetGeoCoordinateAsync();
		}

		public void Start()
		{
			if (monitoring)
			{
				return;
			}

			InitializeLocationManager();
		}

		public void Stop()
		{
			StopMonitoring();
		}

		public void OnLocationChanged(Location location)
		{
			var temp = new GeopositionWrapper(location);
			Geoposition = temp;

			OnPositionChanged(new PositionChangedProxyEventArgs(temp));
		}

		public void OnProviderDisabled(string provider)
		{
			
		}

		public void OnProviderEnabled(string provider)
		{
			
		}

		public void OnStatusChanged(string provider, Availability availability, Bundle extras)
		{
			Status = availability;

			OnStatusChanged(new StatusChangedProxyEventArgs(availability.ToStatus()));
		}

		Availability status;

		public Availability Status
		{
			get
			{
				return status;
			}
			private set
			{
				notifier.Assign(ref status, value);
			}
		}

		public async Task<Address> GetAddressOfLocation(Location location)
		{
			ArgumentValidator.AssertNotNull(location, "location");

			var context = Application.Context;
			Geocoder geocoder = new Geocoder(context);
			IList<Address> addressList = await geocoder.GetFromLocationAsync(
													location.Latitude, location.Longitude, 10);

			Address address = addressList.FirstOrDefault();
			return address;
		}

		Task IMessageSubscriber<ApplicationLifeCycleMessage>.ReceiveMessage(ApplicationLifeCycleMessage message)
		{
			if (monitoring && locationManager != null)
			{
				if (message.State == ApplicationLifeCycleState.Activated)
				{
					locationManager.RequestLocationUpdates(locationProvider, 0, 0, this);
				}
				else if (message.State == ApplicationLifeCycleState.Deactivated)
				{
					locationManager.RemoveUpdates(this);
				}
			}

			return TaskUtility.CreateTaskWithResult();
		}
	}

	public static class PositionAccuracyAndroidExtensions
	{
		public static Accuracy ToAccuracy(this PositionAccuracy positionAccuracy)
		{
			switch (positionAccuracy)
			{
				case PositionAccuracy.Coarse:
					return Accuracy.Coarse;
				case PositionAccuracy.Default:
					return Accuracy.NoRequirement;
				case PositionAccuracy.Fine:
					return Accuracy.Fine;
				case PositionAccuracy.High:
					return Accuracy.High;
				case PositionAccuracy.Low:
					return Accuracy.Low;
				case PositionAccuracy.Medium:
					return Accuracy.Medium;
			}

			throw new ArgumentOutOfRangeException(nameof(positionAccuracy), "Unknown value '" + positionAccuracy + "'");
		}
	}

	public static class PositionStatusExtensions
	{
		public static PositionStatus ToStatus(this Availability availability)
		{
			switch (availability)
			{
				case Availability.Available:
				return PositionStatus.Ready;
				case Availability.OutOfService:
				return PositionStatus.Disabled;
				case Availability.TemporarilyUnavailable:
				return PositionStatus.NoData;
			}

			throw new ArgumentOutOfRangeException(nameof(availability), "Unknown value '" + availability + "'");
		}
	}
}

#endif